# ################################################################# #
#### LOAD LIBRARY AND DEFINE CORE SETTINGS                       ####
# ################################################################# #

### Clear memory
rm(list = ls())

### Load Apollo library
library(apollo)

### Set working directory to the folder of this script
apollo_setWorkDir()

### Initialise code
apollo_initialise()

### Set core controls
apollo_control = list(
  modelDescr      = "Binary logit on Swiss route choice data, written as a user-defined model with apollo_ownModel",
  indivID         = "ID",
  outputDirectory = "output"
)

# ################################################################# #
#### LOAD DATA AND APPLY ANY TRANSFORMATIONS                     ####
# ################################################################# #

### Loading data from package
### if data is to be loaded from a file (e.g. called data.csv),
### the code would be: database = read.csv("data.csv",header=TRUE)
database = apollo_swissRouteChoiceData
### for data dictionary, use ?apollo_swissRouteChoiceData

# ################################################################# #
#### DEFINE MODEL PARAMETERS                                     ####
# ################################################################# #

### Vector of parameters, including any that are kept fixed in estimation
apollo_beta = c(asc_1 = 0,
                b_tt  = 0,
                b_tc  = 0,
                b_hw  = 0,
                b_ch  = 0)

### Vector with names (in quotes) of parameters to be kept fixed at their starting value in apollo_beta, use apollo_fixed = c() if none
apollo_fixed = c()

# ################################################################# #
#### GROUP AND VALIDATE INPUTS                                   ####
# ################################################################# #

apollo_inputs = apollo_validateInputs()

# ################################################################# #
#### DEFINE MODEL AND LIKELIHOOD FUNCTION                        ####
# ################################################################# #

### The model is a binary logit, written out in full and passed to Apollo with apollo_ownModel, rather than using
### apollo_mnl. No gradient is given, so Apollo differentiates the likelihood itself to obtain analytical gradients
apollo_probabilities=function(apollo_beta, apollo_inputs, functionality="estimate"){

  ### Attach inputs and detach after function exit
  apollo_attach(apollo_beta, apollo_inputs)
  on.exit(apollo_detach(apollo_beta, apollo_inputs))

  ### Create list of probabilities P
  P = list()

  ### Utilities of the two routes, and probability of choosing route 1
  V1 = asc_1 + b_tt*tt1 + b_tc*tc1 + b_hw*hw1 + b_ch*ch1
  V2 =         b_tt*tt2 + b_tc*tc2 + b_hw*hw2 + b_ch*ch2
  P1 = exp(V1)/(exp(V1)+exp(V2))

  ### Indicator for route 1 being chosen
  y1 = 1*(choice==1)

  ### Define settings for user-defined model component
  ownModel_settings = list(
    ### Probability of the chosen route in each observation
    likelihood = y1*P1 + (1-y1)*(1-P1),
    ### Probability of the chosen route with all parameters at zero, for LL(0) and the
    ### rho-squared against it
    zero_LL    = 0.5,
    ### Probability of the chosen route with constants only, i.e. its share in the
    ### data, for LL(C) and the rho-squared against it
    shares_LL  = y1*mean(y1) + (1-y1)*(1-mean(y1)),
    ### What apollo_prediction returns: here the probability of choosing route 1
    prediction = P1,
    ### Text reported with the data overview, and with the estimates
    report     = list(
      data  = paste0("Route 1 chosen in ", round(100*mean(y1), 1), "% of cases."),
      param = paste0("Value of travel time: ", round(60*b_tt/b_tc, 2), " CHF/hour."))
  )

  ### Compute probabilities using user-defined model
  P[["model"]] = apollo_ownModel(ownModel_settings, functionality)

  ### Take product across observation for same individual
  P = apollo_panelProd(P, apollo_inputs, functionality)

  ### Prepare and return outputs of function
  P = apollo_prepareProb(P, apollo_inputs, functionality)
  return(P)
}

# ################################################################# #
#### MODEL ESTIMATION                                            ####
# ################################################################# #

model = apollo_estimate(apollo_beta, apollo_fixed, apollo_probabilities, apollo_inputs)

# ################################################################# #
#### MODEL OUTPUTS                                               ####
# ################################################################# #

# ----------------------------------------------------------------- #
#---- FORMATTED OUTPUT (TO SCREEN)                               ----
# ----------------------------------------------------------------- #

apollo_modelOutput(model)

# ----------------------------------------------------------------- #
#---- FORMATTED OUTPUT (TO FILE, using model name)               ----
# ----------------------------------------------------------------- #

apollo_saveOutput(model)

# ################################################################# #
#### THE SAME MODEL, WITH GRADIENTS SUPPLIED BY THE USER          ####
# ################################################################# #

### New model name, so that the outputs of the two models are kept apart
apollo_control$modelName = "MNL_own_model_user_gradient"
apollo_inputs = apollo_validateInputs()

### The derivative of the likelihood with respect to each parameter is now given in gradient, as a list of functions
### named after the parameters to be estimated. As the likelihood is that of a binary logit, each derivative is
### (2*y1-1)*P1*(1-P1) times the difference in the attribute between the two routes, which a helper function computes
apollo_probabilities=function(apollo_beta, apollo_inputs, functionality="estimate"){

  ### Attach inputs and detach after function exit
  apollo_attach(apollo_beta, apollo_inputs)
  on.exit(apollo_detach(apollo_beta, apollo_inputs))

  ### Create list of probabilities P
  P = list()

  ### Utilities of the two routes, and probability of choosing route 1
  V1 = asc_1 + b_tt*tt1 + b_tc*tc1 + b_hw*hw1 + b_ch*ch1
  V2 =         b_tt*tt2 + b_tc*tc2 + b_hw*hw2 + b_ch*ch2
  P1 = exp(V1)/(exp(V1)+exp(V2))

  ### Indicator for route 1 being chosen
  y1 = 1*(choice==1)

  ### Helper function: derivative of the likelihood for a given difference in an
  ### attribute between the two routes
  dLike = function(dx) (2*y1-1)*P1*(1-P1)*dx

  ### Define settings for user-defined model component
  ownModel_settings = list(
    likelihood = y1*P1 + (1-y1)*(1-P1),
    gradient   = list(asc_1 = function() dLike(1),
                      b_tt  = function() dLike(tt1-tt2),
                      b_tc  = function() dLike(tc1-tc2),
                      b_hw  = function() dLike(hw1-hw2),
                      b_ch  = function() dLike(ch1-ch2)),
    zero_LL    = 0.5,
    shares_LL  = y1*mean(y1) + (1-y1)*(1-mean(y1)),
    prediction = P1,
    report     = list(
      data  = paste0("Route 1 chosen in ", round(100*mean(y1), 1), "% of cases."),
      param = paste0("Value of travel time: ", round(60*b_tt/b_tc, 2), " CHF/hour."))
  )

  ### Compute probabilities using user-defined model
  P[["model"]] = apollo_ownModel(ownModel_settings, functionality)

  ### Take product across observation for same individual
  P = apollo_panelProd(P, apollo_inputs, functionality)

  ### Prepare and return outputs of function
  P = apollo_prepareProb(P, apollo_inputs, functionality)
  return(P)
}

model_user_gradient = apollo_estimate(apollo_beta, apollo_fixed, apollo_probabilities, apollo_inputs)

apollo_modelOutput(model_user_gradient)

apollo_saveOutput(model_user_gradient)

# ################################################################# #
##### POST-PROCESSING                                            ####
# ################################################################# #

### Print outputs of additional diagnostics to new output file (remember to close file writing when complete)
apollo_sink()

# ----------------------------------------------------------------- #
#---- COMPARISON OF THE TWO MODELS                               ----
# ----------------------------------------------------------------- #

### The two models are the same, so they give the same estimates, whether Apollo differentiates the likelihood
### itself or uses the gradients given by the user
cbind(no_gradient = model$estimate, user_gradient = model_user_gradient$estimate)

# ----------------------------------------------------------------- #
#---- PREDICTIONS                                                ----
# ----------------------------------------------------------------- #

### Probability of choosing route 1 in each observation, as defined in prediction
predictions = apollo_prediction(model_user_gradient, apollo_probabilities, apollo_inputs)
summary(predictions)

# ----------------------------------------------------------------- #
#---- switch off writing to file                                 ----
# ----------------------------------------------------------------- #

apollo_sink()
